<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="mingzi" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{item.id}}</td>
          <td>{{item.mingzi}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="shanchu(item.id)">删除</button>
            <button @click="bianji (item.id,)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      mingzi: '',
      age: 0,
      sex: '男',
      arr: [],
      id: 1,
    }
  },
  methods: {
    addFn() {
      // console.log(id);
      
      if (this.mingzi.length === 0 || this.age === 0) return alert('请正确输入')
      this.arr.push({
        id: this.length >= 0 ? this.id : this.id++,
        mingzi: this.mingzi,
        sex: this.sex,
        age: this.age,
      })

      // let index = this.arr.findIndex(item => item.id === this.id)


      // this.arr.splice(index, 1, {
      //   mingzi: this.arr.mingzi,
      //   age: this.arr.age,
      //   id: this.arr.id,
      //   sex: this.sex.sex
      // })

    },
    shanchu(id) {
      let index = this.arr.findIndex(item => item.id == id)
      this.arr.splice(index, 1)

    },
    bianji(id) {
      let index = this.arr.findIndex(item => item.id == id)
      this.mingzi = this.arr[index].mingzi
      this.age = this.arr[index].age
      this.id = this.arr[index].id

      // this.arr.splice(index, 0, {
      //   mingzi : this.arr[index].mingzi,
      //   age : this.arr[index].age,
      //   id : this.arr[index].id,
      //   sex:this.sex[index].sex
      // })


    }
  }
}
</script>
